import React, { Component } from 'react';
import {
  StyleSheet, Text, View, TextInput, ScrollView, TouchableOpacity, DeviceEventEmitter, Alert, Image,
} from 'react-native';
import { Icon } from 'native-base';
import produce from 'immer';
import DeviceInfo from 'react-native-device-info';
import ImagePicker from 'react-native-image-crop-picker';
import theme from '../../native-base-theme/variables';
import ZlstIcon from '../../components/zlst-icons';
import { ipConfig } from '../../services/config';
import * as todoService from '../../services/todo';
import { UtilToast, getCurrentPosition } from '../../utils/util-method';

import {
  FormText, FormButtonRadio, FormTitle, FormButtonChoice, FormInput, FormSearchChoiceNoHeader,
  FormTextarea, FormTakephoto, FormSearchChoice, FormSearchKeyword,
} from '../../components';

class AddIncident extends Component {
  static navigationOptions = ({ navigation }) => { // 给导航添加可点击的icon
    const edit = () => DeviceEventEmitter.emit('saveInfoEvent');
    const editor = (
      <View style={{ flexDirection: 'row', paddingLeft: 10 }}>
        <ZlstIcon
          name="fanhui"
          size={24}
          color="white"
          onPress={edit}
        />
      </View>
    );
    const headerStyle = {
      title: navigation.state.params.category ==='incident' ? '故障申报' : '隐患申报',
      headerStyle: { backgroundColor: theme.toolbarDefaultBg },
      headerTintColor: '#FFFFFF',
      headerTitleStyle: {
        fontWeight: 'bold',
        fontSize: 20,
        flex: 1,
        textAlign: 'center',
      },
      headerRight: <View />,
      headerLeft: editor,
    };
    return headerStyle;
  };

  searchUri = '127.0.0.1';

  searchNoHeader = false;

  searHeaderTitle = '请选择';

  searchPlaceholder = '请选择';

  currentChoice = null;

  _choiceConfirm = null;

  failurePic = '';

  extraAddkeywordInfo; // 新增关键字搜索附加参数

  extraInfo;

  failureId = null; // 故障单ID 保存为草稿后 获取草稿后才有值

  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      modalNoHeaderVisible: false,
      keywordModalVisible: false,
      sbid: '',
      sbdh: '',
      category: 'incident',
      equipObjType: '',
      sbbm: '',
      sbmc: '',
      sblx: [
        { name: '临时故障', checked: false, value: '01' },
        { name: '计划大修', checked: false, value: '02' },
        { name: '计划中修', checked: false, value: '03' },
        { name: '计划小修', checked: false, value: '04' },
        { name: '定点检修', checked: false, value: '05' },
        { name: '安全隐患', checked: false, value: '06' },
        { name: '自检自修', checked: false, value: '07' },
      ],
      sslx: [
        { name: '临时故障', checked: false, value: '08' },
        { name: '安全隐患', checked: false, value: '09' },
      ],
      wzms: '',
      yhlx: [
        { name: '人的不安全行为', checked: false, value: '1' },
        { name: '设施的不安全状态', checked: false, value: '3' },
        { name: '管理缺陷', checked: false, value: '4' },
      ],
      yhdj: [
        { name: '重大隐患', checked: false, value: 'A' },
        { name: '一般隐患', checked: false, value: 'B' },
      ],
      ry: '',
      jjcd: [{ name: '高', checked: false, value: 'A' }, { name: '中', checked: false, value: 'B' }, { name: '低', checked: false, value: 'C' }],
      wxbz: { id: '', name: '' },
      keyword: { id: '', name: '' },
      facilitiesCategory: { id: '', name: '' },
      bumen: { id: '', name: '' },
      facilities: { id: '', name: '' },
      sbms: '',
      images: [],
    };
  }

  componentDidMount() {
    if (this.props.navigation.state.params.flag === 'update') {
      this.updateInit(this.props.navigation.state.params.data);
    } else {
      const {
        sbid, sbbm, sbmc, equipObjType, maintOrgId, maintOrgName, category,
      } = this.props.navigation.state.params;
      const mCategory = category == null ? 'incident' : category;
      this.setState({
        sbid,
        category: mCategory,
        sbbm,
        sbmc,
        equipObjType,
        wxbz: { id: maintOrgId, name: maintOrgName },
      });
      this.fetchCode();
    }
    DeviceEventEmitter.addListener('saveInfoEvent', this.saveInfoEvent);
    DeviceEventEmitter.addListener('getDeviceInfoEvent', this.getDeviceInfoEvent);
  }

  componentWillUnmount() {
    DeviceEventEmitter.removeAllListeners('saveInfoEvent');
    DeviceEventEmitter.removeAllListeners('getDeviceInfoEvent');
    ImagePicker.clean().then(() => {
      console.log('removed all tmp images from tmp directory');
    }).catch(e => {
      console.log(e);
    });
  }

  updateInit = (data) => {
    this.setState(produce(draft => {
      draft.sbdh = data.failureCode;
      draft.equipObjType = data.objType;
      if (data.failureType == '08') {
        draft.category = 'facilitiesIncident';
        draft.facilitiesCategory = { id: data.objType, name: data.facilityTypeName };
        draft.facilities = { id: data.facilityId, name: data.facilityName };
        draft.sslx[0].checked = true;
        draft.wzms = data.location;
        switch (data.failureLevel) {
          case 'A':
            draft.jjcd[0].checked = true;
            break;
          case 'B':
            draft.jjcd[1].checked = true;
            break;
          case 'C':
            draft.jjcd[2].checked = true;
            break;
          default:
            draft.jjcd[2].checked = true;
        }
      } else if (data.failureType == '09') {
        draft.category = 'facilitiesIncident';
        draft.sslx[1].checked = true;
        draft.facilitiesCategory = { id: data.objType, name: data.facilityTypeName };
        draft.facilities = { id: data.facilityId, name: data.facilityName };
        switch (data.hiddenDangerType) {
          case '1':
            draft.yhlx[0].checked = true;
            break;
          case '3':
            draft.yhlx[1].checked = true;
            break;
          case '4':
            draft.yhlx[2].checked = true;
            break;
          default:
            draft.yhlx[0].checked = true;
        }
        switch (data.failureLevel) {
          case 'A':
            draft.yhdj[0].checked = true;
            break;
          case 'B':
            draft.yhdj[1].checked = true;
            break;
          default:
            draft.yhdj[1].checked = true;
        }
        draft.wxbz.id = data.maintOrgId;
        draft.wxbz.name = data.maintOrgIdDesc;
        draft.wzms = data.location;
        draft.ry = data.name;
        draft.bumen.id = data.hiddenDangerOrgId;
        draft.bumen.name = data.hiddenDangerOrgIdDesc;
      } else {
        draft.sbid = data.equipmentId;
        draft.sbbm = data.equipmentCode;
        draft.sbmc = data.equipmentName;
        switch (data.failureLevel) {
          case 'A':
            draft.jjcd[0].checked = true;
            break;
          case 'B':
            draft.jjcd[1].checked = true;
            break;
          case 'C':
            draft.jjcd[2].checked = true;
            break;
          default:
            draft.jjcd[2].checked = true;
        }
        switch (data.failureType) {
          case '01':
            draft.sblx[0].checked = true;
            break;
          case '02':
            draft.sblx[1].checked = true;
            break;
          case '03':
            draft.sblx[2].checked = true;
            break;
          case '04':
            draft.sblx[3].checked = true;
            break;
          case '05':
            draft.sblx[4].checked = true;
            break;
          case '06':
            draft.sblx[5].checked = true;
            break;
          case '07':
            draft.sblx[6].checked = true;
            break;
          default:
            draft.sblx[0].checked = true;
        }
        draft.wxbz.id = data.maintOrgId;
        draft.wxbz.name = data.maintOrgIdDesc;
      }
      draft.keyword.id = data.failureKeywordsId;
      draft.keyword.name = data.failureKeywords;
      const _sbms = data.failureDesc.indexOf(' ') > -1 ? data.failureDesc.split(' ')[0] : '';
      draft.sbms = _sbms;
      this.failureId = data.failureId;
      if (data.failurePic) {
        this.failurePic = data.failurePic;
        draft.images = [{ uri: `${ipConfig.url(`${todoService.serverName}/logistics/fileController/download/`)}${data.failurePic}?token=${global.__TOKEN_ACCESS__}`, type: 'multipart/form-data', name: `${new Date().getTime()}.png` }];
      }
    }));
  }

  getDeviceInfoEvent = async (code) => {
    if (this.state.category == 'incident') {
      try {
        DeviceEventEmitter.emit('showLoading', true);
        const data = await todoService.getDeviceInfo({ equipmentCode: code });
        if (data) {
          this.setState({
            sbbm: data.code, sbmc: data.name, sbid: data.id, equipObjType: data.equipObjType, wxbz: { id: data.maintOrgId, name: data.maintOrgName },
          });
        } else {
          UtilToast(`扫描出的条码${code}没有对应的设备信息`, 'danger');
        }
        DeviceEventEmitter.emit('showLoading', false);
      } catch (error) {
        DeviceEventEmitter.emit('showLoading', false);
      }
    } else {
      try {
        DeviceEventEmitter.emit('showLoading', true);
        const data = await todoService.getFacilitiesInfo({ facilityId: code });
        if (data) {
          this.setState({
            facilitiesCategory: { id: data.objType, name: data.facilityTypeName },
            facilities: { id: data.facilityId, name: data.facilityName },
            equipObjType: data.objType,
          });
        } else {
          UtilToast(`扫描出的条码${code}没有对应的设施信息`, 'danger');
        }
        DeviceEventEmitter.emit('showLoading', false);
      } catch (error) {
        DeviceEventEmitter.emit('showLoading', false);
      }
    }
  }

  saveInfoEvent = () => {
    if (this.props.navigation.state.params.flag === 'update') {
      this.props.navigation.goBack();
      if (this.props.navigation.state.params._refresh) {
        this.props.navigation.state.params._refresh();
      }
    } else {
      Alert.alert(
        '提示',
        '退出需要保存草稿吗',
        [
          {
            text: '不保存',
            style: 'cancel',
            onPress: () => {
              if (this.failureId) {
                this.delDraft(true, this.failureId);
              } else {
                this.props.navigation.goBack();
              }
            },
          },
          {
            text: '保存',
            onPress: () => {
              this.confirmSub('01');
            },
          },
        ],
      );
    }
  }

  delDraft = async (ifGoback, delId) => {
    try {
      DeviceEventEmitter.emit('showLoading', true);
      const { data } = await todoService.delDraft({ failureId: delId });
      DeviceEventEmitter.emit('showLoading', false);
      if (!data) {
        UtilToast('草稿删除失败', 'danger');
      }
      if (ifGoback) {
        this.props.navigation.goBack();
      }
    } catch (error) {
      DeviceEventEmitter.emit('showLoading', false);
      if (ifGoback) {
        this.props.navigation.goBack();
      }
    }
  }

  // 获取故障单号和草稿信息
  fetchCode = async () => {
    try {
      DeviceEventEmitter.emit('showLoading', true);
      const { code } = await todoService.autoCreateFailureCode();
      const { data } = await todoService.findDraftDetail();
      if (data && this.state.category == 'incident' && data.failureType != '08' && data.failureType != '09') {
        DeviceEventEmitter.emit('showLoading', false);
        Alert.alert(
          '提示',
          '是否显示草稿',
          [
            {
              text: '取消',
              style: 'cancel',
              onPress: () => {
                this.setState(produce(draft => {
                  draft.sbdh = code;
                  draft.sblx[0].checked = true;
                  draft.jjcd[2].checked = true;
                  draft.sslx[0].checked = true;
                  draft.yhlx[0].checked = true;
                  draft.yhdj[0].checked = true;
                  this.delDraft(false, data.failureId);
                }));
              },
            },
            {
              text: '确定',
              onPress: () => {
                this.setState(produce(draft => {
                  draft.sbdh = data.failureCode;
                  if (this.props.navigation.state.params.flag === 'add') {
                    draft.sbid = data.equipmentId;
                    draft.sbbm = data.equipmentCode;
                    draft.sbmc = data.equipmentName;
                    draft.equipObjType = data.objType;
                  }
                  switch (data.failureLevel) {
                    case 'A':
                      draft.jjcd[0].checked = true;
                      break;
                    case 'B':
                      draft.jjcd[1].checked = true;
                      break;
                    case 'C':
                      draft.jjcd[2].checked = true;
                      break;
                    default:
                      draft.jjcd[2].checked = true;
                  }
                  switch (data.failureType) {
                    case '01':
                      draft.sblx[0].checked = true;
                      break;
                    case '02':
                      draft.sblx[1].checked = true;
                      break;
                    case '03':
                      draft.sblx[2].checked = true;
                      break;
                    case '04':
                      draft.sblx[3].checked = true;
                      break;
                    case '05':
                      draft.sblx[4].checked = true;
                      break;
                    case '06':
                      draft.sblx[5].checked = true;
                      break;
                    case '07':
                      draft.sblx[6].checked = true;
                      break;
                    default:
                      draft.sblx[0].checked = true;
                  }
                  draft.wxbz.id = data.maintOrgId;
                  draft.wxbz.name = data.maintOrgIdDesc;
                  draft.keyword.id = data.failureKeywordsId;
                  draft.keyword.name = data.failureKeywords;
                  if (data.failureDesc) {
                    draft.sbms = data.failureDesc;
                  }
                  this.failureId = data.failureId;
                  if (data.failurePic) {
                    this.failurePic = data.failurePic;
                    draft.images = [{ uri: `${ipConfig.url(`${todoService.serverName}/logistics/fileController/download/`)}${data.failurePic}?token=${global.__TOKEN_ACCESS__}`, type: 'multipart/form-data', name: `${new Date().getTime()}.png` }];
                  }
                }));
              },
            },
          ],
        );
      } else if (data && this.state.category !== 'incident' && data.failureType == '09') {
        DeviceEventEmitter.emit('showLoading', false);
        Alert.alert(
          '提示',
          '是否显示草稿',
          [
            {
              text: '取消',
              style: 'cancel',
              onPress: () => {
                this.setState(produce(draft => {
                  draft.sbdh = code;
                  draft.sblx[0].checked = true;
                  draft.jjcd[2].checked = true;
                  draft.sslx[0].checked = true;
                  draft.yhlx[0].checked = true;
                  draft.yhdj[0].checked = true;
                  this.delDraft(false, data.failureId);
                }));
              },
            },
            {
              text: '确定',
              onPress: () => {
                this.setState(produce(draft => {
                  draft.sbdh = data.failureCode;
                  draft.facilitiesCategory = { id: data.objType, name: data.facilityTypeName };
                  draft.facilities = { id: data.facilityId, name: data.facilityName };
                  draft.equipObjType = data.objType;
                  draft.sslx[1].checked = true;
                  switch (data.hiddenDangerType) {
                    case '1':
                      draft.yhlx[0].checked = true;
                      break;
                    case '3':
                      draft.yhlx[1].checked = true;
                      break;
                    case '4':
                      draft.yhlx[2].checked = true;
                      break;
                    default:
                      draft.yhlx[0].checked = true;
                  }
                  switch (data.failureLevel) {
                    case 'A':
                      draft.yhdj[0].checked = true;
                      break;
                    case 'B':
                      draft.yhdj[1].checked = true;
                      break;
                    default:
                      draft.yhdj[1].checked = true;
                  }
                  draft.wxbz.id = data.maintOrgId;
                  draft.wxbz.name = data.maintOrgIdDesc;
                  draft.keyword.id = data.failureKeywordsId;
                  draft.keyword.name = data.failureKeywords;
                  draft.wzms = data.location;
                  draft.ry = data.name;
                  draft.bumen.id = data.hiddenDangerOrgId;
                  draft.bumen.name = data.hiddenDangerOrgIdDesc;
                  if (data.failureDesc) {
                    draft.sbms = data.failureDesc;
                  }
                  this.failureId = data.failureId;
                  if (data.failurePic) {
                    this.failurePic = data.failurePic;
                    draft.images = [{ uri: `${ipConfig.url(`${todoService.serverName}/logistics/fileController/download/`)}${data.failurePic}?token=${global.__TOKEN_ACCESS__}`, type: 'multipart/form-data', name: `${new Date().getTime()}.png` }];
                  }
                }));
              },
            },
          ],
        );
      } else if (data && this.state.category !== 'incident' && data.failureType == '08') {
        DeviceEventEmitter.emit('showLoading', false);
        Alert.alert(
          '提示',
          '是否显示草稿',
          [
            {
              text: '取消',
              style: 'cancel',
              onPress: () => {
                this.setState(produce(draft => {
                  draft.sbdh = code;
                  draft.sblx[0].checked = true;
                  draft.jjcd[2].checked = true;
                  draft.sslx[0].checked = true;
                  draft.yhlx[0].checked = true;
                  draft.yhdj[0].checked = true;
                  this.delDraft(false, data.failureId);
                }));
              },
            },
            {
              text: '确定',
              onPress: () => {
                this.setState(produce(draft => {
                  draft.sbdh = data.failureCode;
                  draft.facilitiesCategory = { id: data.objType, name: data.facilityTypeName };
                  draft.facilities = { id: data.facilityId, name: data.facilityName };
                  draft.equipObjType = data.objType;
                  draft.wzms = data.location;
                  draft.sslx[0].checked = true;
                  switch (data.failureLevel) {
                    case 'A':
                      draft.jjcd[0].checked = true;
                      break;
                    case 'B':
                      draft.jjcd[1].checked = true;
                      break;
                    case 'C':
                      draft.jjcd[2].checked = true;
                      break;
                    default:
                      draft.jjcd[2].checked = true;
                  }
                  draft.keyword.id = data.failureKeywordsId;
                  draft.keyword.name = data.failureKeywords;
                  if (data.failureDesc) {
                    draft.sbms = data.failureDesc;
                  }
                  this.failureId = data.failureId;
                  if (data.failurePic) {
                    this.failurePic = data.failurePic;
                    draft.images = [{ uri: `${ipConfig.url(`${todoService.serverName}/logistics/fileController/download/`)}${data.failurePic}?token=${global.__TOKEN_ACCESS__}`, type: 'multipart/form-data', name: `${new Date().getTime()}.png` }];
                  }
                }));
              },
            },
          ],
        );
      } else {
        this.setState(produce(draft => {
          draft.sbdh = code;
          draft.sblx[0].checked = true;
          draft.jjcd[2].checked = true;
          draft.sslx[0].checked = true;
          draft.yhlx[0].checked = true;
          draft.yhdj[0].checked = true;
        }));
        DeviceEventEmitter.emit('showLoading', false);
      }
    } catch (e) {
      console.log(e);
      DeviceEventEmitter.emit('showLoading', false);
      this.props.navigation.goBack();
    }
  }

  sblx = (v) => {
    let _sblx = null;
    this.state.sblx.forEach((data) => {
      if (data.checked) {
        _sblx = data.value;
      }
    });
    const sblx = this.state.sblx.map(it => ({
      ...it,
      checked: it.name === v.name,
    }));

    this.setState(produce(draft => {
      draft.sblx = sblx;
      if (v.value == '06' || _sblx == '06') {
        draft.wxbz.id = '';
        draft.wxbz.name = '';
      }
    }));
  }

  sslx = (v) => {
    const sslx = this.state.sslx.map(it => ({
      ...it,
      checked: it.name === v.name,
    }));

    this.setState(produce(draft => {
      draft.sslx = sslx;
    }));
  }

  yhlx = (v) => {
    const yhlx = this.state.yhlx.map(it => ({
      ...it,
      checked: it.name === v.name,
    }));

    this.setState(produce(draft => {
      draft.yhlx = yhlx;
    }));
  }

  yhdj = (v) => {
    const yhdj = this.state.yhdj.map(it => ({
      ...it,
      checked: it.name === v.name,
    }));

    this.setState(produce(draft => {
      draft.yhdj = yhdj;
    }));
  }

  jjcd = (v) => {
    const jjcd = this.state.jjcd.map(it => ({
      ...it,
      checked: it.name === v.name,
    }));

    this.setState(produce(draft => {
      draft.jjcd = jjcd;
    }));
  }

  wxbz = () => {
    this._choiceConfirm = (it) => {
      this.setState({ wxbz: { id: it[0].id, name: it[0].name } });
    };
    let _sblx = null;
    this.state.sblx.forEach((it) => {
      if (it.checked) {
        _sblx = it.value;
      }
    });
    if (_sblx == '06' || this.state.category !== 'incident') { // 安全隐患
      this.searchUri = '/api-ms/system/organizations/findOrgByType?orgType=Safe';
      this.searchNoHeader = true;
      this.searHeaderTitle = '安全部门';
      this._showNoHeaderModal();
    } else {
      this.searchUri = `${todoService.serverName}/device/fualt/queryMaintOrg`;
      this.searchNoHeader = false;
      this._showModal();
    }
  }

  keyword = () => {
    const {
      sslx,
      yhlx,
    } = this.state;

    let _sslx = null;
    sslx.forEach((it) => {
      if (it.checked) {
        _sslx = it.value;
      }
    });

    let _yhlx = null;
    yhlx.forEach((it) => {
      if (it.checked) {
        _yhlx = it.value;
      }
    });
    if (this.state.category === 'facilitiesIncident' && _sslx == '09' && (_yhlx === '1' || _yhlx === '4')) {
      this._choiceConfirm = (it) => {
        this.setState({ keyword: { id: it[0].id, name: it[0].name } });
      };
      this.searchUri = 'incidentKeywordUrl';
      this.searchNoHeader = false;
      this.searchPlaceholder = '请输入故障关键字';
      this.extraAddkeywordInfo = { active: 0, createdBy: global.user.id, objType: '', failureType: _sslx, hiddenDangerType: _yhlx };
      this.extraInfo = { objType: '', failureType: _sslx, hiddenDangerType: _yhlx };
      this._showKeywordModal();
    } else if (this.state.equipObjType) {
      this._choiceConfirm = (it) => {
        this.setState({ keyword: { id: it[0].id, name: it[0].name } });
      };
      this.searchUri = 'incidentKeywordUrl';
      this.searchNoHeader = false;
      this.searchPlaceholder = '请输入故障关键字';
      this.extraAddkeywordInfo = { active: 0, createdBy: global.user.id, objType: this.state.equipObjType, failureType: '', hiddenDangerType: '' };
      this.extraInfo = { objType: this.state.equipObjType, failureType: '', hiddenDangerType: '' };
      this._showKeywordModal();
    } else {
      UtilToast('请选择设备信息', 'danger');
    }
  }

  facilitiesCategory = () => {
    this._choiceConfirm = (it) => {
      this.setState({ facilitiesCategory: { id: it[0].id, name: it[0].name }, equipObjType: it[0].id, facilities: { id: '', name: '' }, keyword: { id: '', name: '' } });
    };
    this.searchUri = 'facilitiesCategory';
    this.searchNoHeader = false;
    this.searchPlaceholder = '请输入设施类型名称';
    this.extraAddkeywordInfo = {};
    this.extraInfo = {};
    this._showKeywordModal();
  }

  bumen = () => {
    // this._choiceConfirm = (it) => {
    //   this.setState({ bumen: { id: it[0].id, name: it[0].name } });
    // };
    // this.searchUri = 'bumen';
    // this.searchNoHeader = false;
    // this.searchPlaceholder = '请输入部门名称';
    // this.extraAddkeywordInfo = {};
    // this.extraInfo = {};
    // this._showKeywordModal();

    this._choiceConfirm = (it) => {
      this.setState({ bumen: { id: it[0].id, name: it[0].name } });
    };
    this.searchUri = '/api-ms/system/organizations/findOrg';
    this.searchNoHeader = true;
    this.searHeaderTitle = '选择部门';

    this._showModal();
//    this._showNoHeaderModal();
  }

  facilities = () => {
    if (this.state.facilitiesCategory.id) {
      this._choiceConfirm = (it) => {
        this.setState({ facilities: { id: it[0].id, name: it[0].name } });
      };
      this.searchUri = 'facilities';
      this.searchNoHeader = false;
      this.searchPlaceholder = '请输入设施名称';
      this.extraAddkeywordInfo = { objType: this.state.facilitiesCategory.id };
      this.extraInfo = { objType: this.state.facilitiesCategory.id };
      this._showKeywordModal();
    } else {
      UtilToast('请选择设施类型', 'danger');
    }
  }

  // 设备信息选择
  sbxz = () => {
    this._choiceConfirm = (it) => {
      let _sblx = null;
      this.state.sblx.forEach((data) => {
        if (data.checked) {
          _sblx = data.value;
        }
      });
      if (_sblx == '06') { // 安全隐患
        this.setState({
          sbbm: it[0].code, sbmc: it[0].name, sbid: it[0].id, equipObjType: it[0].equipObjType, wxbz: { id: it[0].safeOrgId, name: it[0].safeOrgName }, keyword: { id: '', name: '' },
        });
      } else {
        this.setState({
          sbbm: it[0].code, sbmc: it[0].name, sbid: it[0].id, equipObjType: it[0].equipObjType, wxbz: { id: it[0].maintOrgId, name: it[0].maintOrgName }, keyword: { id: '', name: '' },
        });
      }
    };
    this.searchUri = `${todoService.serverName}/device/equipment/queryEquipmentByparams`;
    this.searchNoHeader = true;
    this.searHeaderTitle = '设备信息';
    this._showModal();
  }

  iconClick = () => {
    global.navigation.navigate({ routeName: 'Qrcode', params: { flag: 'newIncident' } });
  }

  addImage = (uri) => {
    this.setState(produce(draft => {
      // draft.images.push(uri);
      draft.images = [uri];
    }));
  }

  delImage = (index) => {
    Alert.alert(
      '提示',
      '确定删除照片',
      [
        {
          text: '取消',
          style: 'cancel',
        },
        {
          text: '确定',
          onPress: () => {
            this.setState(produce(draft => {
              draft.images.splice(index, 1);
            }));
            this.failurePic = '';
          },
        },
      ],
    );
  }

  _showModal = () => {
    this.setState({
      modalVisible: true,
    });
  }

  _showNoHeaderModal = () => {
    this.setState({
      modalNoHeaderVisible: true,
    });
  }

  _showKeywordModal = () => {
    this.setState({
      keywordModalVisible: true,
    });
  }

  showBigImage = () => {
    DeviceEventEmitter.emit('showBigImage', { show: true, url: this.state.images[0].uri });
  }

  _cancelModal = () => {
    this.setState({ modalVisible: false });
  }

  _cancelNoHeaderModal = () => {
    this.setState({ modalNoHeaderVisible: false });
  }

  _cancelKeywordModal = () => {
    this.setState({ keywordModalVisible: false });
  }

  confirmSub = async (stepCode) => {
    const {
      wxbz,
      sbms,
      facilitiesCategory,
      facilities,
      sbid,
      keyword,
      wzms,
      sslx,
      yhlx,
      ry,
      bumen,
    } = this.state;

    let _sslx = null;
    sslx.forEach((it) => {
      if (it.checked) {
        _sslx = it.value;
      }
    });

    let _yhlx = null;
    yhlx.forEach((it) => {
      if (it.checked) {
        _yhlx = it.value;
      }
    });

    // else if (this.state.category ==='facilitiesIncident' && _sslx == '08' && keyword.id === '') {
    //   UtilToast('请选择故障关键字', 'danger');
    // } else if (this.state.category ==='facilitiesIncident' && _sslx == '09' && _yhlx === '3' && keyword.id === '') {
    //   UtilToast('请选择故障关键字', 'danger');
    // }

    if (this.state.category ==='incident' && sbid === '') {
      UtilToast('请选择设备信息', 'danger');
    } else if (this.state.category ==='incident' && wxbz.id === '') {
      UtilToast('请选择维修班组', 'danger');
    } else if (this.state.category ==='facilitiesIncident' && _sslx == '09' && wxbz.id === '') {
      UtilToast('请选择安全部门', 'danger');
    } else if (this.state.category ==='facilitiesIncident' && wzms === '') {
      UtilToast('请输入位置描述', 'danger');
    } else if (this.state.category ==='facilitiesIncident' && _sslx == '08' && facilitiesCategory.id === '') {
      UtilToast('请选择设施类别', 'danger');
    } else if (this.state.category ==='facilitiesIncident' && _sslx == '08' && facilities.id === '') {
      UtilToast('请选择设施名称', 'danger');
    } else if (this.state.category ==='facilitiesIncident' && _sslx == '09' && _yhlx === '3' && facilitiesCategory.id === '') {
      UtilToast('请选择设施类别', 'danger');
    } else if (this.state.category ==='facilitiesIncident' && _sslx == '09' && _yhlx === '3' && facilities.id === '') {
      UtilToast('请选择设施名称', 'danger');
    } else if (this.state.category ==='facilitiesIncident' && _sslx == '09' && _yhlx === '1' && ry === '') {
      UtilToast('请输人员', 'danger');
    } else if (this.state.category ==='facilitiesIncident' && _sslx == '09' && _yhlx === '1' && bumen.id === '') {
      UtilToast('请输选择部门', 'danger');
    } else if (this.state.category ==='facilitiesIncident' && _sslx == '09' && _yhlx === '4' && bumen.id === '') {
      UtilToast('请输选择部门', 'danger');
    } else if (keyword.id === '') {
      UtilToast('请选择故障关键字', 'danger');
    } else if (stepCode === '01') {
      this.submit(stepCode);
    } else {
      Alert.alert(
        '提示',
        '确定提交',
        [
          { text: '取消', style: 'cancel' },
          {
            text: '确定',
            onPress: () => {
              this.submit(stepCode);
            },
          },
        ],
      );
    }
  }

  submit = async (stepCode) => {
    const {
      sbid,
      sbdh,
      sblx,
      jjcd,
      wxbz,
      sbms,
      keyword,
      facilities,
      equipObjType,
      images,
      wzms,
      sslx,
      yhlx,
      ry,
      bumen,
      yhdj,
    } = this.state;
    DeviceEventEmitter.emit('showLoading', true);
    try {
      if (!this.failurePic && images.length > 0) {
        const imageResult = await todoService.uploadPic(images);
        this.failurePic = imageResult.data.fileId;
      }
      let _jjcd = null;
      jjcd.forEach((it) => {
        if (it.checked) {
          _jjcd = it.value;
        }
      });
      let _sblx = null;
      sblx.forEach((it) => {
        if (it.checked) {
          _sblx = it.value;
        }
      });

      let _sslx = null;
      sslx.forEach((it) => {
        if (it.checked) {
          _sslx = it.value;
        }
      });

      let _yhlx = null;
      yhlx.forEach((it) => {
        if (it.checked) {
          _yhlx = it.value;
        }
      });

      let _yhdj = null;
      yhdj.forEach((it) => {
        if (it.checked) {
          _yhdj = it.value;
        }
      });

      const mac = await DeviceInfo.getMACAddress().then();
      const carrier = DeviceInfo.getCarrier();
      const mobileModel = DeviceInfo.getModel();
      const { location } = await getCurrentPosition();
      const payload = {
        carrier,
        description: sbms,
        equipmentId: sbid,
        facilityId: facilities.id,
        failureId: this.failureId,
        failureCode: sbdh,
        failureLevel: this.state.category == 'incident' ? _jjcd : _yhdj,
        failureType: this.state.category == 'incident' ? _sblx : _sslx,
        failureKeywordsId: keyword.id,
        failureKeywords: keyword.name,
        latitude: location && location.coords && location.coords.latitude,
        longitude: location && location.coords && location.coords.longitude,
        equipObjType,
        mac,
        maintOrgId: wxbz.id,
        mobileModel,
        picture: this.failurePic,
        stepCode,
        location: wzms,
        hiddenDangerType: this.state.category ==='facilitiesIncident' && _sslx == '09' ? _yhlx : '',
        name: ry,
        hiddenDangerOrgId: bumen.id,
      };
      const result = await todoService.declareFailure(payload);
      if (result.success) {
        UtilToast('处理成功', 'success');
        this.props.navigation.goBack();
        DeviceEventEmitter.emit('refreshPageEvent');
        if (this.props.navigation.state.params._refresh) {
          this.props.navigation.state.params._refresh();
        }
        if (this.state.wxbz.id == '-1') {
          const params = {
            fromNavigation: true,
            id: result.failureId,
            code: result.failureCode,
          };
          global.navigation.navigate({ routeName: 'Info', params });
        }
      }
    } catch (error) {
      DeviceEventEmitter.emit('showLoading', false);
    }
    DeviceEventEmitter.emit('showLoading', false);
  }

  render() {
    let _sslx = null;
    this.state.sslx.forEach((it) => {
      if (it.checked) {
        _sslx = it.value;
      }
    });
    let _yhlx = null;
    this.state.yhlx.forEach((it) => {
      if (it.checked) {
        _yhlx = it.value;
      }
    });

    // let showKeyword = false;
    // if (this.state.category ==='incident') {
    //   showKeyword = true;
    // } else if (this.state.category ==='facilitiesIncident' && _sslx == '08') {
    //   showKeyword = true;
    // } else if (this.state.category ==='facilitiesIncident' && _sslx == '09' && _yhlx === '3') {
    //   showKeyword = true;
    // }

    return (
      <View style={{ flex: 1, flexDirection: 'column' }}>
        <View>
          {this.state.modalNoHeaderVisible && (
            <FormSearchChoiceNoHeader
              onClose={this._cancelNoHeaderModal}
              searchUri={this.searchUri}
              type="radio"
              title={this.searHeaderTitle}
              searchNoHeader={this.searchNoHeader}
              choiceConfirm={this._choiceConfirm}
            />
          )}
        </View>
        {this.state.modalVisible && (
          <FormSearchChoice
            onClose={this._cancelModal}
            searchUri={this.searchUri}
            type="radio"
            title={this.searHeaderTitle}
            searchNoHeader={this.searchNoHeader}
            choiceConfirm={this._choiceConfirm}
          />
        )}
        {this.state.keywordModalVisible && (
          <FormSearchKeyword
            onClose={this._cancelKeywordModal}
            searchUri={this.searchUri}
            type="radio"
            title={this.searHeaderTitle}
            extraAddkeywordInfo={this.extraAddkeywordInfo}
            extraInfo={this.extraInfo}
            searchNoHeader={this.searchNoHeader}
            choiceConfirm={this._choiceConfirm}
            searchPlaceholder={this.searchPlaceholder}
          />
        )}
        <ScrollView style={{ flex: 1 }}>
          <View style={styles.container}>
            <FormText name="申报单号" value={this.state.sbdh} />
            {
              this.state.category === 'incident' ? (
                <View>
                  <FormTitle name="设备信息" iconName="saoma" iconClick={this.iconClick} />
                  <TouchableOpacity style={styles.sbxnContainer} onPress={this.sbxz}>
                    <View style={{ flex: 0.9, flexDirection: 'column' }}>
                      <View style={{ flexDirection: 'row', padding: 5, alignItems: 'center' }}>
                        <View style={{ flex: 0.3 }}>
                          <Text style={{ color: 'white' }}>设备编码：</Text>
                        </View>
                        <View style={{ flex: 0.7, flexWrap: 'wrap' }}>
                          <TextInput
                            editable={false}
                            style={{ padding: 0, margin: 0, color: 'white' }}
                            onChangeText={(text) => this.setState({ sbbm: text })}
                            value={this.state.sbbm}
                          />
                        </View>
                      </View>
                      <View style={{ flexDirection: 'row', padding: 5, alignItems: 'center' }}>
                        <View style={{ flex: 0.3 }}>
                          <Text style={{ color: 'white' }}>设备名称：</Text>
                        </View>
                        <View style={{ flex: 0.7, flexWrap: 'wrap' }}>
                          <TextInput
                            editable={false}
                            style={{ padding: 0, margin: 0, color: 'white' }}
                            onChangeText={(text) => this.setState({ sbmc: text })}
                            value={this.state.sbmc}
                          />
                        </View>
                      </View>
                    </View>
                    <TouchableOpacity
                      onPress={this.sbxz}
                      style={styles.arrow}
                    >
                      <Icon name="arrow-forward" style={{ color: 'white' }} />
                    </TouchableOpacity>
                  </TouchableOpacity>
                </View>
              ) : (
                <View>
                  <View>
                    <FormText name="隐患类型" />
                    <FormButtonRadio datas={this.state.sslx} _click={this.sslx} />
                  </View>
                  <FormText name="位置描述" />
                  <FormTextarea
                    value={this.state.wzms}
                    _onChangeText={(text) => this.setState({ wzms: text })}
                  />
                  {_sslx === '08' && (
                    <View>
                      <FormText name="设施类型" />
                      <FormButtonChoice name={this.state.facilitiesCategory.name} _click={this.facilitiesCategory} />
                      <FormTitle name="设施名称" iconName="saoma" iconClick={this.iconClick} />
                      <FormButtonChoice name={this.state.facilities.name} _click={this.facilities} />
                    </View>
                  )}
                  {_sslx === '09' && (
                    <View>
                      <FormText name="隐患类型" />
                      <FormButtonRadio datas={this.state.yhlx} _click={this.yhlx} />
                    </View>
                  )}
                  {_sslx === '09' && _yhlx === '1' && (
                    <View>
                      <FormTitle name="人员" />
                      <FormInput
                        placeholder="填写内容"
                        keyboardType="default"
                        value={this.state.ry}
                        _onChangeText={(text) => this.setState({ ry: text })}
                      />
                      <FormText name="部门" />
                      <FormButtonChoice name={this.state.bumen.name} _click={this.bumen} />
                      {/* <FormTitle name="人员" iconName="saoma" iconClick={this.iconClick} />
                      <FormButtonChoice name={this.state.facilities.name} _click={this.facilities} /> */}
                    </View>
                  )}
                  {_sslx === '09' && _yhlx === '3' && (
                    <View>
                      <FormText name="设施类型" />
                      <FormButtonChoice name={this.state.facilitiesCategory.name} _click={this.facilitiesCategory} />
                      <FormTitle name="设施名称" iconName="saoma" iconClick={this.iconClick} />
                      <FormButtonChoice name={this.state.facilities.name} _click={this.facilities} />
                    </View>
                  )}
                  {_sslx === '09' && _yhlx === '4' && (
                    <View>
                      <FormText name="部门" />
                      <FormButtonChoice name={this.state.bumen.name} _click={this.bumen} />
                    </View>
                  )}
                </View>
              )
            }

            {/* {
              showKeyword && (
                <View>
                  <FormText name="故障关键字" />
                  <FormButtonChoice name={this.state.keyword.name} _click={this.keyword} />
                </View>
              )
            } */}
            <FormText name={this.state.category === 'incident' ? '故障关键字' : '隐患关键字'} />
            <FormButtonChoice name={this.state.keyword.name} _click={this.keyword} />
            <FormText name="补充说明" />
            <FormTextarea
              value={this.state.sbms}
              _onChangeText={(text) => this.setState({ sbms: text })}
            />
            {
              this.state.category === 'incident' && (
                <View>
                  <FormText name="申报类型" />
                  <FormButtonRadio datas={this.state.sblx} _click={this.sblx} />
                  <FormText name="紧急程度" />
                  <FormButtonRadio datas={this.state.jjcd} _click={this.jjcd} />
                  <FormText name="维修班组" />
                  <FormButtonChoice name={this.state.wxbz.name} _click={this.wxbz} />
                </View>
              )
            }
            {
              this.state.category !== 'incident' && _sslx === '08' && (
                <View>
                  <FormText name="紧急程度" />
                  <FormButtonRadio datas={this.state.jjcd} _click={this.jjcd} />
                </View>
              )
            }
            {
              this.state.category !== 'incident' && _sslx === '09' && (
                <View>
                  <FormText name="隐患等级" />
                  <FormButtonRadio datas={this.state.yhdj} _click={this.yhdj} />
                  <FormText name="安全部门" />
                  <FormButtonChoice name={this.state.wxbz.name} _click={this.wxbz} />
                </View>
              )
            }
            <FormText name={this.state.category === 'incident' ? '故障图片' : '隐患图片'} />
            <FormTakephoto
              datas={this.state.images}
              addImage={this.addImage}
              showBigImage={this.showBigImage}
              delImage={this.delImage}
            />
          </View>
        </ScrollView>
        <TouchableOpacity style={styles.footer} onPress={() => this.confirmSub('02')} activeOpacity={0.8}>
          <Image
            source={require('../../../assets/images/btn-cut-line-xxx.png')}
            style={{ width: '100%', height: 2, alignItems: 'center' }}
            resizeMode="stretch"
            resizeMethod="auto"
          />
          <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <Text style={{ color: 'white' }}>提交</Text>
          </View>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: theme.myPrimary,
  },
  imageModalClose: {
    fontSize: 30,
    color: 'white',
    left: 10,
    top: 10,
    position: 'absolute',
    zIndex: 1,
  },
  arrow: {
    flex: 0.1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: 10,
    paddingBottom: 10,
  },
  sbxnContainer: {
    borderWidth: 1,
    borderRadius: 2,
    borderStyle: 'solid',
    flexDirection: 'row',
    alignItems: 'center',
    borderColor: 'rgba(219,219,219,0.52)',
    justifyContent: 'center',
    margin: 5,
  },
  footer: {
    width: '100%',
    flexDirection: 'column',
    backgroundColor: theme.myPrimary,
    height: 48,
  },
});

export default AddIncident;
